<?php
/**
 * Created by PhpStorm.
 * User: caoguangyang
 * Date: 2023-01-22
 * Time: 16:41
 */

namespace App\Services\Goods;

use App\Inputs\GoodsListInput;
use App\Models\Goods\Footprint;
use App\Models\Goods\Goods;
use App\Models\Goods\GoodsAttribute;
use App\Models\Goods\GoodsProduct;
use App\Models\Goods\GoodsSpecification;
use App\Models\Goods\Issue;
use App\Services\BaseServices;
use Illuminate\Database\Eloquent\Builder;

class GoodsServices extends BaseServices
{

    /**
     * 获取商品信息
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function getGoods($id) {
        return Goods::query()->find($id);
    }

    /**
     * 获取商品属性
     * @param int $goodsId
     * @return \App\Models\BaseModel[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getGoodsAttribute(int $goodsId) {
        return GoodsAttribute::query()->where('goods_id', $goodsId)
            ->where('deleted', 0)->get();
    }

    /**
     * 获取商品规格
     * @param int $goodsId
     * @return \App\Models\BaseModel[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public function getGoodsSpecification(int $goodsId) {
        $spec = GoodsSpecification::query()->where("goods_id", $goodsId)
            ->where("deleted", 0)->get()->groupBy("specification");
        return $spec->map(function ($v, $k) {
           return ['name'=> $k, 'valueList' => $v];
        })->values();
    }

    public function saveFootPrint($userId, $goodsId) {
        $footPrint = new Footprint();
        $footPrint->fill(["user_id" => $userId, 'goods_id' => $goodsId]);
        return $footPrint->save();
    }

    public function getGoodsIssue(int $page = 1, int $limit = 4) {
        return Issue::query()->forPage($page, $limit)->get();
    }

    /**
     * 获取商品sku
     * @param int $goodsId
     * @return \App\Models\BaseModel[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getGoodsProduct(int $goodsId) {
        return GoodsProduct::query()->where('goods_id', $goodsId)
            ->where('deleted', 0)->get();
    }

    /**
     * 获取在售的商品数量
     * @return int
     */
    public function countGoodsOnSale() {
        return Goods::query()->where("is_on_sale", 1)
            ->where("deleted", 0)->count('id');
    }

    // 商品列表
    public function listGoods(GoodsListInput $input, $columns) {
        $query = $this->getQueryByGoodsFilter($input);
        if (!empty($input->categoryId)) {
            $query = $query->where('category_id', $input->categoryId);
        }
        //return $query->orderBy($sort, $order)->paginate($limit, $columns, 'page', $page);
        return $query->orderBy($input->sort, $input->order)->paginate($input->limit, $columns, 'page', $input->page);
    }

    public function getQueryByGoodsFilter($input) {
        // 拼接where语句
        $query = Goods::query()->where('is_on_sale', 1)->where('deleted', 0);
        if (!empty($input->brandId)) {
            $query = $query->where('brand_id', $input->brandId);
        }
        if (!is_null($input->isNew)) {
            $query = $query->where('is_new', $input->isNew);
        }
        if (!is_null($input->isHot)) {
            $query = $query->where('is_hot', $input->isHot);
        }
        if (!empty($input->keyword)) {
            $query = $query->where(function (Builder $query) use ($input) {
                $query->where('keywords', 'like', "%$input->keyword%")
                    ->orWhere('name', 'like', "%$input->keyword%");
            });
        }
        return $query;
    }

    public function listL2Category($input) {
        $query = $this->getQueryByGoodsFilter($input);
        $categoryIds = $query->select(['category_id'])->pluck('category_id')->unique()->toArray();
        return CategoryServices::getInstance()->getL2ListByIds($categoryIds);
    }

    public function getGoodsListByIds(array $ids) {
        if (empty($ids)) {
            return collect();
        }
        return Goods::query()->whereIn('id', $ids)->get();
    }
    
    public function getGoodsProductById(int $id) {
        return GoodsProduct::query()->find($id);
    }

    public function getGoodsProductsByIds(array $ids) {
        if (empty($ids)) {
            return collect();
        }
        return GoodsProduct::query()->whereIn('id', $ids)->get();
    }

    public function reduceStock($productId, $num) {
        return GoodsProduct::query()->where('id', $productId)->where('number', '>=', $num)
            ->decrement('number', $num);
    }

    public function addStock($productId, $num) {
        $product = $this->getGoodsProductById($productId);
        $product->number = $product->number + $num;
        return $product->cas();
    }
}